//app.js
const request = require('./utils/request.js')
App({
  request: request,
  onLaunch: function () {
    var _this = this;
    wx.onAppShow(res => {
      _this.globalData.obj = res;
    });
    this.login();
  },
  onShow(){
    var open_id = wx.getStorageSync('open_id');
    if(!open_id){
      this.login();
    }
  },
  login: function(){
    var _this = this;
    // 登录
    wx.login({
      success: res => {
        if (res.errMsg == 'login:ok') {
          this.request.requestPostApi({
            url: this.apiHost + "login/login",
            params: { code: res.code },
            success: function (response) {
              wx.setStorageSync('open_id', response.data);
              _this.getUserInfo();
            }
          });
        } else {
          wx.showToast({
            title: res.errMsg,
          })
        }
      }
    })
  },

  getUserInfo: function () {
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              this.userInfoReadyCallback(res)
            }
          })
        }
      }
    })
  },
  userInfoReadyCallback: function (res) {
    this.globalData.userInfo = JSON.parse(res.rawData);
    var open_id = wx.getStorageSync('open_id')
    var params = {
      user_info: res.rawData,
      open_id
    }
    this.request.requestPostApi({
      url: this.apiHost + "login/save-user-info",
      params,
    });
  },
  globalData: {
    userInfo: null,
    auto_go: 1,
    obj: {}
  },

  onHide: function(){
    this.globalData.auto_go = 1;
  },
   /**
   * 定义的接口域名
   */
  apiHost: 'https://photo.chenshiqi.com.cn/'
  // apiHost: 'http://local.photo.com/'
})